package com.wyd.System.Controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyd.System.Bean.Specialty;
import com.wyd.System.Service.SpecialtyService;
import com.wyd.System.Vo.SpecialtyVo;
import com.wyd.handler.BusinessException;
import com.wyd.response.Result;
import com.wyd.response.ResultCode;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 文永达
 * @since 2020-12-25
 */
@RestController
@RequestMapping("/System/specialty")
public class SpecialtyController {
    @Autowired
    private SpecialtyService specialtyService;

    @ApiOperation(value = "查询专业及人数",notes = "从专业表中分组查询学生人数")
    @GetMapping("/findSpecialty")
    public Result findSpecialty(){
        List<Specialty> specialties=specialtyService.findSpecialty();
        if(specialties.size()==0){
            throw new BusinessException(ResultCode.INSTITUTE_NOT_FOUND_EXCEPTION.getCode(),
                    ResultCode.SPECIALTY_NOT_FOUND_EXCEPTION.getMessage());
        }
        return Result.ok().data("specialties",specialties);
    }

    @ApiOperation("分页查询专业列表")
    @PostMapping("/findSpecialtyList")
    public Result findSpecialtyList(@RequestParam(required = true,defaultValue = "1")Integer current,
                                    @RequestParam(required = true,defaultValue = "6")Integer size,
                                    @RequestBody SpecialtyVo specialtyVo){
        Page<Specialty> page = new Page<>(current,size);
        QueryWrapper<Specialty> wrapper = getWrapper(specialtyVo);
        IPage<Specialty> specialtyPage = specialtyService.findSpecialtyList(page,wrapper);
        long total = specialtyPage.getTotal();
        List<Specialty> records = specialtyPage.getRecords();
        return Result.ok().data("total",total).data("records",records);
    }

    private QueryWrapper<Specialty> getWrapper(SpecialtyVo specialtyVo){
        QueryWrapper<Specialty> queryWrapper = new QueryWrapper<>();
        if(specialtyVo!=null){
            if(!StringUtils.isEmpty(specialtyVo.getSpecialtyName())){
                queryWrapper.eq("specialty_name",specialtyVo.getSpecialtyName());
            }
            if(!StringUtils.isEmpty(specialtyVo.getInstituteName())){
                queryWrapper.eq("institute_name",specialtyVo.getInstituteName());
            }
        }
        return queryWrapper;
    }
}

